#!/bin/sh
# small programm to compare dns zones on different servers during a migration
VERBOSE=no

shortName ()
{
  local TESTNAME=$1
  printf "${TESTNAME:0:`expr ${#TESTNAME} - 1`}"
}

testArec ()
{
  local RECNAME=`shortName $1` 
  local VALUE=$2
  case ${RECNAME:0:11} in
    (sipman2-dns|sipman3-dns) SKIP=yes ;;
    (*)
      TEST=`host $RECNAME $SERVER2 | grep "has address"`
      if [ "`echo $TEST | grep "$RECNAME has address $VALUE"`" = "" ]; then
        echo "  Error $RECNAME $VALUE not found ==>"
        TEST2=`echo $TEST | grep "has address"`
        if [ "$TEST2" != "" ]; then
          echo "    $TEST2"
        fi
#       sleep 2
      elif [ "$VERBOSE" = "yes" ]; then
        echo "  Tested $RECNAME $VALUE, oke."
      fi
    ;;
  esac
}

testCnameRec ()
{
  local RECNAME=`shortName $1`
  local VALUE=$2
# case ${RECNAME:0:11} in
#   (sipman2-dns|sipman3-dns) SKIP=yes ;;
#   (*)
      TEST=`host $RECNAME $SERVER2 | grep "is an alias for"`
      if [ "`echo $TEST | grep "$RECNAME is an alias for $VALUE"`" = "" ]; then
        echo "  Error $RECNAME $VALUE not found ==>"
        TEST2=`echo $TEST | grep "is an alias for"`
        if [ "$TEST2" != "" ]; then
          echo "    $TEST2"
        fi
        TEST2=`host $RECNAME $SERVER1 | grep "has address"`
        if [ "$TEST2" != "" ]; then
          echo "    $TEST2"
        fi
#       sleep 2
      elif [ "$VERBOSE" = "yes" ]; then
        echo "  Tested $RECNAME $VALUE, oke."
      fi
#   ;;
# esac

}

SERVER1=10.1.1.15
SERVER2=10.1.1.112
TMPFILE=/var/tmp/testzones-$$.txt
ZONEFILE=$1
RUNDNS=$2
if [ "$RUNDNS" = "dns" ]; then
  /var/sipman3/main/bin/sipman-starter.sh local upd-dns
fi
if [ ! -f "$ZONEFILE" ] || [ "$ZONEFILE" = "" ]; then
  echo "Usage: $0 zonefile (dns).
        This tool will compare the zonefiles between server $SERVER1 and $SERVER2."
  exit
fi
grep "type master" $ZONEFILE | sed 's/\"//g' | while read V1 TZONE REST
do
  host -al $TZONE $SERVER1 > $TMPFILE
  echo "Testing zone $TZONE, `cat $TMPFILE | wc -l` lines."
# cat $TMPFILE
  cat $TMPFILE | while read RECNAME TTL IN RECTYPE VALUE
  do
    if [ "$IN" = "IN" ]; then
      case $RECTYPE in
        (A)       testArec $RECNAME $VALUE ;;
        (CNAME)   testCnameRec $RECNAME $VALUE ;;
        (NS|SOA|PTR)  SKIP=yes ;;
        (*)       echo "Skipping $RECNAME $RECTYPE $VALUE."
      esac
    fi
  done 
done
rm $TMPFILE
